package com.jz.digital.listener;

import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.jz.digital.bean.BaseEntity;
import com.jz.digital.utils.ErrorCode;
import com.jz.digital.utils.LogUtils;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Copyright (c) 2019 深圳市爱都科技有限公司. All rights reserved.
 */
public abstract class ApiCallback<T extends BaseEntity> implements Callback<T>, NetCallback<T> {
    private static final String TAG = "ApiCallback";
    //错误码
    private int mCode;

    @Override
    public void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) {
        BaseEntity entity = response.body();
        String responseStr = response.toString();
        //保存每一次返回的response，用于定位是否是服务器的问题
        if (!TextUtils.isEmpty(responseStr)) {
            LogUtils.d(TAG, "onResponse responseStr = " + responseStr);
        } else {
            LogUtils.d(TAG, "onResponse responseStr 为空");
        }

        int code = -1;
        String message = "";
        if (entity != null) {
            code = entity.getCode();
            if (entity.getMessage() != null) {
                LogUtils.d(TAG, "response.body():BaseEntity -- status " +
                        entity.getCode() + ",message" + entity.getMessage());
                message = entity.getMessage();
            }
        } else {
            String url = response.raw().request().url().toString();
            if (!TextUtils.isEmpty(url) && url.endsWith("/")) {
                url = url.substring(0, url.length() - 1);
            }
        }
        mCode = code;
        if (code == ErrorCode.CODE_SUCCESS || code == ErrorCode.CODE_NOT_ALLOW_SIMULTANEOUS_RECEIPT) {
            onSuccess(response.body());
        } else {
            onError(null, code, message);
        }
    }

    @Override
    public void onFailure(@NonNull Call<T> call, @NonNull Throwable t) {
        LogUtils.d(TAG, "onFailure t = " + t.toString());
        onError(t, -1, "");
    }


    public int getCode() {
        return mCode;
    }
}
